package com.qfmy.web.app.service.impl.novel;

import com.qfmy.common.exception.BaseException;
import com.qfmy.common.login.LoginUser;
import com.qfmy.common.login.LoginUserHolder;
import com.qfmy.common.result.ResultCodeEnum;
import com.qfmy.model.entity.novel.History;
import com.qfmy.model.vo.novel.HistoryVo;
import com.qfmy.web.app.mapper.novel.HistoryMapper;
import com.qfmy.web.app.service.novel.HistoryService;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 清风明月
 * @Package com.qfmy.web.app.service.impl.novel
 * @date 2025/9/11
 * @description 用户阅读历史
 */
@Service
public  class HistoryServiceImpl implements HistoryService {

    /**
     * 注入mapper
     */
    @Autowired
    private HistoryMapper historyMapper;

    /**
     * 获取最新阅读
     * @return
     */
    @Override
    public HistoryVo getNewestHistory() {
        //获取当前用户id
        Long userId = getUserId();

        //判断
        if (userId == null || userId < 0) {
            return null;
        }

        //根据用户id获取最新阅读
        History history = historyMapper.getNewestHistory(userId);

        //创建vo对象
        HistoryVo historyVo = new HistoryVo();
        if(history != null)
        {
           //进行对象转换
            BeanUtils.copyProperties(history,historyVo);
            return historyVo;
        }
        return null;
    }

    /**
     * 分页获取阅读历史
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public List<HistoryVo> getHistories(Integer pageNum, Integer pageSize) {
        //校验参数
        if(pageNum == null || pageNum < 1)
        {
            pageNum = 1;
            pageSize = 15;
        }

        //获取当前用户id
        Long userId = getUserId();

        //校验
        if (userId == null || userId < 0) {
            return Collections.emptyList();
        }

        //计算分页
        int offset = (pageNum - 1) * pageSize;
        List<History> histories = historyMapper.getHistoriesByPage(userId, offset, pageSize);
        //转换
        return convertToVo(histories);
    }

    /**
     * 删除阅读历史
     * @param historyId
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHistory(Integer historyId) {
        historyMapper.deleteHistory(historyId);
    }

    /**
     * 清空所有阅读历史
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void clearAllHistories() {
        //获取当前用户id
        Long userId = getUserId();
        if (userId == null || userId < 0) {
            return;
        }
        //删除
        historyMapper.clearAllHistories(userId);
    }

    /**
     * 保存阅读历史
     *
     * @param novelId
     * @param chapterIndex
     * @param page
     * @param title
     */
    @Override
    public void saveHistory(Integer novelId, Integer chapterIndex, double page, String title) {
        //获取当前用户id
        Long userId = getUserId();
        if (userId == null || userId < 0) {
            return;
        }
       //根据用户id和小说id查询阅读历史
        History history = historyMapper.selectHistory(userId, novelId);
        //判断是否存在
        if(history != null)
        {
            //更新阅读历史
            historyMapper.UpdateHistory(novelId, chapterIndex, page, userId, title);
        }else {
            //创建阅读历史
            History his = new History();
            his.setChapterIndex(chapterIndex);
            his.setNovelId(novelId);
            his.setUserId(userId);
            his.setLastReadTime(new Date());
            his.setUpdateTime(new Date());
            his.setPage(page);
            his.setTitle(title);
            historyMapper.saveHistory(his);
        }
    }

    /**
     * 根据小说id获取阅读历史
     *
     * @param novelId
     * @return
     */
    @Override
    public HistoryVo getHistoriesByNovelId(Integer novelId) {
        //获取当前用户id
        Long userId = getUserId();
        if (userId == null || userId < 0) {
            return null;
        }
        //根据用户id和小说id获取阅读历史
        History histories = historyMapper.selectHistory(userId, novelId);
        //转换
        return histories == null ? null : new HistoryVo(histories.getHistoryId(), histories.getChapterIndex(), histories.getLastReadTime(), histories.getPage(), histories.getNovel(), histories.getTitle());
    }
    /**
     * 转换
     * @param histories
     * @return
     */
    @Nullable
    @Contract(pure = true)
    private List<HistoryVo> convertToVo(List<History> histories) {
        //校验集合
        if(histories != null && !histories.isEmpty())
        {
            //创建vo对象
            return histories.stream().map(history -> {
                HistoryVo historyVo = new HistoryVo();
                BeanUtils.copyProperties(history,historyVo);
                return historyVo;
            }).collect(Collectors.toList());
        }
        return Collections.emptyList();
    }

    /**
     * 获取用户id
     */
    @Nullable
    @Contract(pure = true)
    private Long getUserId() {
        //获取当前用户id
        LoginUser loginUser = LoginUserHolder.getLoginUser();
        if(loginUser == null)
        {
            throw new BaseException(ResultCodeEnum.ILLEGAL_REQUEST);
        }
        return loginUser.getUserId();
    }
}
